<template>
  <div class="main-container">
    <div class="welcome">
      <button class="toregist" @click="toregist" :class="{ hiddenregistbtn: isHiddenRegistBtn }">
        没有账号，点击注册
      </button>
      <button class="tologin" @click="tologin" :class="{ loginbtn: isLoginBtn }">
        已有帐号，直接登录
      </button>

      <div class="container" :class="{
          aftermove: isAftermove,
          container: isContainer
        }">
        <!-- 登录区域 -->
        <div class="logincontainer" :class="{ hiddenlogin: isHiddenLogin }">
          <!-- 登录标题 -->
          <span class="tittle">登录</span>
          <!-- 图标 -->
          <div class="icon-list">
            <a-icon type="qq" />
            <a-icon type="wechat" />
            <a-icon type="weibo-circle" />
          </div>
          <a-form id="login-form-area" :form="loginForm" class="login-form" @submit="login">
            <div id="account">
              <a-form-item>
                <a-input class="input-username" v-decorator="[
                    'loginUserName',
                    {
                      rules: [
                        { required: true, message: '请输入账号' },
                        {
                          pattern: /^\d{5,12}$/,
                          message: '账号必须为5~12位数字'
                        }
                      ]
                    }
                  ]" placeholder="Account">
                  <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
            </div>
            <div id="password">
              <a-form-item>
                <a-input class="input-password" v-decorator="[
                    'loginPassword',
                    {
                      rules: [
                        { required: true, message: '请输入密码' },
                        {
                          pattern: /^[a-zA-Z0-9]{8,16}$/,
                          message: '密码必须为8~16位字母数字'
                        }
                      ]
                    }
                  ]" type="password" placeholder="Password">
                  <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
            </div>
            <a-button type="primary" html-type="submit" class="login-form-button">
              登录
            </a-button>
          </a-form>
        </div>
        <!-- 注册 -->
        <div class="registercontainer" :class="{ hiddenregist: isHiddenRegist }">
          <!-- 注册标题 -->
          <span class="tittle">注册</span>
          <!-- 图标 -->
          <div class="icon-list">
            <a-icon type="qq" />
            <a-icon type="wechat" />
            <a-icon type="weibo-circle" />
          </div>
          <a-form id="regist-form-area" :form="registForm" class="login-form" @submit="regist">
            <div id="account">
              <a-form-item>
                <a-input class="input-username" v-decorator="[
                    'userName',
                    {
                      rules: [{ validator: handleAccountIsRepeat }]
                    }
                  ]" placeholder="Account">
                  <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
            </div>
            <div id="password">
              <a-form-item>
                <a-input class="input-password" v-decorator="[
                    'password',
                    {
                      rules: [
                        { required: true, message: '请输入你的密码' },
                        {
                          pattern: /^[a-zA-Z0-9]{8,16}$/,
                          message: '密码必须为8~16位字母数字'
                        }
                      ]
                    }
                  ]" type="password" placeholder="Password">
                  <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
            </div>
            <div id="email">
              <a-form-item>
                <a-input class="input-email" v-decorator="[
                    'email',
                    {
                      rules: [{ validator: handleEmailIsRepeat }]
                    }
                  ]" placeholder="Email">
                  <a-icon slot="prefix" type="mail" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
            </div>
            <div class="code">
              <a-form-item>
                <a-input class="input-code" v-decorator="[
                    'code',
                    {
                      rules: [
                        {
                          required: true,
                          message: '请输入4位数字验证码'
                        },
                        {
                          pattern: /^[a-zA-Z0-9]{5}$/,
                          message: '请输入格式正确的验证码'
                        }
                      ]
                    }
                  ]" placeholder="请输入验证码">
                  <a-icon slot="prefix" type="block" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
              <div class="code-btn">
                <a-button :loading="loading" class="code-btn" @click="showModal(), sendCode()">{{ yzm }}</a-button>
              </div>
            </div>
            <a-modal title="请完成安全验证" :visible="visible" :footer="null" :width="360" :destroyOnClose="true">
              <div class="safeTest">
                <slide-verify :l="42" :r="10" :w="310" :h="155" slider-text="向右拖动滑块填充拼图" @success="onSuccess"
                  @fail="onFail" @refresh="onRefresh"></slide-verify>
              </div>
            </a-modal>
            <a-button type="primary" html-type="submit" class="login-form-button">
              注册
            </a-button>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { encryptedData, decryptData } from "../../util/RSA";
import MD5encryption from "../../util/md5";
import _ from "lodash";
import {
  get_rsa_key,
  register,
  verify_account,
  verify_email,
  get_code
} from "@/request/api/user";
export default {
  name: "login",
  data () {
    return {
      isAftermove: false,
      isContainer: true,
      isHiddenRegistBtn: false,
      isLoginBtn: false,
      isHiddenLogin: false,
      isHiddenRegist: true,
      loginForm: this.$form.createForm(this, "loginForm"),
      registForm: this.$form.createForm(this, "registForm"),
      //   标记账号是否重复
      isAccountPepeat: false,
      //  标记邮箱是否重复
      isEmailRepeat: false,
      //  安全验证弹出层是否可见
      visible: false,
      yzm: "获取验证码",
      disabled: false,
      loading: false,
      publicKey:''
    };
  },
  computed: {
    // publicKey () {
    //   if (Cookies.get("publicKey") != undefined) {
    //     return Cookies.get("publicKey")
    //   } else {
    //     get_rsa_key()
    //       .then(res => {
    //           console.log(res);
    //         Cookies.set("publicKey", res.publicKey,{expires: 1/8})
    //       })
    //       .catch(error => {
    //         console.log(error);
    //       });
    //       return Cookies.get("publicKey")
    //   }
    // }
  },
  methods: {
    toregist () {
      this.isAftermove = true;
      this.isContainer = false;
      this.isHiddenRegistBtn = true;
      this.isLoginBtn = true;
      this.isHiddenLogin = true;
      this.isHiddenRegist = false;
    },
    tologin () {
      this.isAftermove = false;
      this.isContainer = true;
      this.isHiddenRegistBtn = false;
      this.isLoginBtn = false;
      this.isHiddenLogin = false;
      this.isHiddenRegist = true;
    },
    // 登录按钮触发事件函数
    login (e) {
      e.preventDefault();
      this.loginForm.validateFields((error, values) => {
        if (!error) {
          // 从表单获取账号和密码并加密密码
          let account = this.loginForm.getFieldValue("loginUserName");
          let MD5password = MD5encryption(
            this.loginForm.getFieldValue("loginPassword")
          );
          let password = encryptedData(MD5password, this.publicKey);
          // 将请求发给vuex中的action[login]进行处理
          this.$store
            .dispatch("login", { account, password })
            .then(res => {
                console.log(res);
              if (res.code == 0) {
                  this.$store.commit("SET_ACCOUNT",account)
                // Cookies.set("account", account)
                this.$message.info("登陆成功");
                this.$router.push({ path: "/" });
              } else {
                this.$message.error("登陆失败，请重试");
              }
            })
            .catch((error) => {
              console.log(error)
            });
        }
      });
    },

    //发请求查询账号是否重复，对请求进行防抖处理

    // Verify_account: _.debounce(function() {
    //   let account = this.registForm.getFieldValue("userName");
    //   console.log(account);
    //   //  console.log("账号",this.registForm.getFieldValue("userName"));
    //   if (account !== undefined && account != "") {
    //     // let account = parseInt(account);
    //     verify_account({ account }).then(data => {
    //       console.log("响应数据", data);
    //       if (data.code == 1) {
    //           this.is
    //       }
    //     });
    //   }

    // }, 1000),

    //查询邮箱是否重复，对请求进行防抖处理
    // Verify_email: _.debounce(function() {
    //   let email = this.registForm.getFieldValue("email");
    //   if (email !== undefined && email != "") {
    //     verify_email({ email }).then(data => {
    //       console.log("响应数据", data);
    //       if (data.code == 1) {
    //         this.isEmailRepeat = true}
    //     });
    //   }
    // }, 1000),
    // 自定义注册账号校验规则
    handleAccountIsRepeat (isAccountPepeat, value, callback) {
      let reg = /^\d{5,12}$/;
      if (!value) {
        callback("请输入账号");
      } else if (!reg.test(value)) {
        callback("账号必须为5~12位数字");
      } else {
        verify_account({ account: value }).then(data => {
          //   console.log("响应数据", data);
          if (data.code == 1) {
            callback("账号重复，换一个吧");
          } else {
            callback();
          }
        });
      }
    },
    // 自定义邮箱校验规则
    handleEmailIsRepeat (rule, value, callback) {
      let reg = /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/;
      if (!value) {
        callback("请输入邮箱");
      } else if (!reg.test(value)) {
        callback("请输入正确的邮箱");
      } else {
        _.debounce(
          verify_email({ email: value }).then(data => {
            //   console.log("响应数据", data);
            if (data.code == 1) {
              callback("邮箱已被注册");
            } else {
              callback();
            }
          }),
          2000
        );
      }
    },
    //拼图成功回调
    onSuccess () {
      let email = this.registForm.getFieldValue("email");
      setTimeout(() => {
        this.visible = false;
        get_code({ email })
          .then(res => {
            console.log(res);
            if (res.code == 0) this.$message.success("获取验证码成功！");
            else this.$message.error("获取验证码失败！");
          })
          .catch(error => {
            console.log(error);
            this.$message.error("获取验证码失败！");
          });
      }, 500);
    },
    // 拼图失败回调，暂时没用
    onFail () { },
    // 刷新图片回调，暂时没用
    onRefresh () { },
    // 展示安全验证拼图页面
    showModal () {
      this.visible = true;
    },
    // 获取验证码按钮,60s冷却
    sendCode () {
      let time = 60;
      this.loading = true;
      this.yzm = time + "s";
      time--;
      this.disabled = true;
      let timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.loading = false;
          this.yzm = "获取验证码";
          this.disabled = false;
        } else {
          this.loading = true;
          this.yzm = time + "s";
          time--;
          this.disabled = true;
        }
      }, 1000);
    },
    // 发起注册请求
    regist (e) {
      this.registForm.validateFields((error, values) => {
        if (!error) {
          let account = values.userName;
          //  公钥加密密码
          let MD5password = MD5encryption(values.password);
          let password = encryptedData(MD5password, this.publicKey);
          let email = values.email;
          let code = values.code;
          register({ account, password, email, code })
            .then(res => {
              if (res.code == 0) {
                console.log("注册表单数据", account, password, email, code);

                this.$message.success("注册成功，请登录");
                this.registForm.resetFields();
                this.tologin();
              } else {
                console.log(res);
                this.$message.error(res.msg);
              }
            })
            .catch(error => {
              console.log(error);
              this.$message.error("注册失败！");
            });
        }
      });
      e.preventDefault();
    }
  },

  watch: {},
  // 在实例创建之前得到私钥
  mounted () {
    // 发请求获得公钥
    get_rsa_key()
      .then(res => {
       this.publicKey = res.publicKey
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
.main-container {
  background: url("../../assets/bg.jpg") no-repeat;
  width: 100%;
  height: 100%;
  position: fixed;
  background-size: 100% 100%;
}

.btn {
  width: 30px;
  height: 30px;
  z-index: 6;
}

.welcome {
  width: 850px;
  height: 515px;
  min-width: 650px;
  opacity: 1;
  position: relative;
  top: 50%;
  left: 50%;
  overflow: hidden;
  transform: translate(-50%, -50%);
  border-radius: 10px;
  box-shadow: 0 0.9rem 1.7rem rgba(0, 0, 0.25), 0 0.7rem 0.7rem rgba(0, 0, 0.22);
}

/* 一开始在左侧 */
.container {
  width: 425px;
  height: 100%;
  position: absolute;
  left: 0;
  background-color: #f6f8fa;
  transition: all 0.5s;
}
/* 移动到右侧注册 */
.aftermove {
  width: 425px;
  height: 100%;
  position: absolute;
  left: 425px;
  background-color: #f6f8fa;
  transition: all 0.5s;
}

.tittle {
  margin-top: 10px;
  font-size: larger;
  font-weight: bold;
  text-align: center;
  display: block;
}

.hiddenregist {
  display: none;
}

.toregist {
  margin: 0px;
  padding: 0px;
  /*自定义边框*/
  border: 0px;
  /*消除默认点击蓝色边框效果*/
  outline: none;
  width: 185px;
  right: 30px;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  background: linear-gradient(to left, #09bada, #3587e4);
  border-radius: 50px;
  text-align: center;
  line-height: 40px;
  color: whitesmoke;
  font-weight: bold;
}
.tologin {
  margin: 0px;
  padding: 0px;
  /*自定义边框*/
  border: 0px;
  /*消除默认点击蓝色边框效果*/
  outline: none;
  width: 200px;
  height: 40px;
  position: absolute;
  left: 211px;
  top: 50%;
  transform: translate(-50%, -50%);
  background: linear-gradient(to left, #09bada, #3587e4);
  border-radius: 50px;
  text-align: center;
  line-height: 40px;
  color: whitesmoke;
  font-weight: bold;
  display: none;
}
/* 隐藏注册按钮 */
.hiddenregistbtn {
  display: none;
}
/* 显示登录按钮 */
.loginbtn {
  display: inline;
  transition: all 0.5s;
}

/* 隐藏登录区域 */
.hiddenlogin {
  display: none;
  transition: all 0.5s;
}

/* 显示注册区域 */
.displayregist {
  display: none;
  transition: all 0.5s;
}

/*表单样式 */
.tittle {
  margin-top: 20px;
  text-align: center;
  font-size: 30px;
  font-weight: bolder;
}

/*图标样式  */
.icon-list {
  margin: 30px auto 30px auto;
  width: 150px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/*覆盖icon-font样式*/
.icon-list:before {
    content: "";
}
.icon-list .anticon {
  font-size: 26px;
}

.login-form {
  display: flex;
  justify-content: left;
  flex-direction: column;
  align-items: left;
}
.input-username,
.input-password,
.input-email {
  width: 270px;
}

#account,
#password,
#email {
  width: 270px;
  height: 60px;
}

/* 表单大小和位置 */
#login-form-area,
#regist-form-area {
  width: 270px;
  height: 350px;
  margin: 50px auto 0 auto;
}
/* 登录按钮样式 */
#login-form-area .login-form-button,
#regist-form-area .login-form-button {
  width: 130px;
  height: 30px;
  margin-top: 15px;
  align-self: center;
}
/* 验证码输入框 */
.code {
  width: 300px;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.code:after {
  /*伪元素是行内元素 正常浏览器清除浮动方法*/
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

.input-code {
  width: 150px;
}
.code-btn {
  width: 80px;
  height: 30px;
  margin-top: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.code-btn button {
  margin-top: 5px;
}
.ant-btn.ant-btn-loading:not(.ant-btn-circle):not(.ant-btn-circle-outline):not(.ant-btn-icon-only) {
  padding: 0;
}
.code-btn span {
  display: inline;
  width: 78px;
  text-align: center;
}

.safeTest {
  margin: 0 auto;
}
</style>
